﻿// ======================================================================
//   
//           Copyright (C) 2019-2020 湖南心莱信息科技有限公司    
//           All rights reserved
//   
//           filename : TokenApi.cs
//           description :
//   
//           created by 雪雁 at  2019-03-13 10:03
//           Mail: wenqiang.li@xin-lai.com
//           QQ群：85318032（技术交流）
//           Blog：http://www.cnblogs.com/codelove/
//           GitHub：https://github.com/xin-lai
//           Home：http://xin-lai.com
//   
// ======================================================================

using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Monkey.Dingtalk.SDK.Helper;
using Monkey.Dingtalk.SDK.Token.Dto;

namespace Monkey.Dingtalk.SDK.Token
{
  public class TokenApi : ApiBase
  {
    private readonly IConfiguration _configuration;

    public TokenApi(ILogger<TokenApi> logger, IConfiguration configuration, IServiceProvider serviceProvider) : base(
      logger, serviceProvider
    ) {
      _configuration = configuration;
    }

    public async Task<GetTokenResult> GetToken() {
      var appKey    = _configuration["Dingtalk:AppKey"];
      var appSecret = _configuration["Dingtalk:AppSecret"];
      if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(appSecret)) {
        throw new Exception("AppKey和AppSecret必须在settings文件中配置");
      }

      return await Get<GetTokenResult>($"gettoken?appkey={appKey}&appsecret={appSecret}");
    }

    public async Task<GetTokenResult> GetCorpToken() {
      var authCorpId   = _configuration["Dingtalk:AuthCorpId"];
      var customKey    = _configuration["Dingtalk:CustomKey"];
      var customSecret = _configuration["Dingtalk:CustomSecret"];
      if (string.IsNullOrEmpty(authCorpId) || string.IsNullOrEmpty(customKey)) {
        throw new Exception("AuthCorpId和CustomKey必须在settings文件中配置");
      }

      var suiteTicket = new Random().Next(10000, 1000000);
      var timeStamp   = DateTime.Now.ConvertToTimeStamp();
      var signature   = WebUtility.UrlEncode(Sign(customSecret, $"{timeStamp}\n{suiteTicket}"));
      return await Post<GetTokenResult>(
               $"service/get_corp_token?signature={signature}&timestamp={timeStamp}&suiteTicket={suiteTicket}&accessKey={customKey}",
               new {auth_corpid = authCorpId}
             );
    }

    private static string Sign(string secret, string message) {
      byte[]    keyByte      = Encoding.UTF8.GetBytes(secret);
      byte[]    messageBytes = Encoding.UTF8.GetBytes(message);
      using var hmac256      = new HMACSHA256(keyByte);
      byte[]    hashMessage  = hmac256.ComputeHash(messageBytes);
      return Convert.ToBase64String(hashMessage);
    }
  }
}